package org.csu.mypetstore.web.Filter;

import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.tools.WebLog;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class ViewFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

 //       System.out.println("1122");

        Item item = (Item) ((HttpServletRequest)req).getSession().getAttribute("item");
        Cart cart = (Cart) ((HttpServletRequest)req).getSession().getAttribute("cart");
        Product product = (Product) ((HttpServletRequest)req).getSession().getAttribute("product");
        Category category = (Category) ((HttpServletRequest)req).getSession().getAttribute("category");
        Account account = (Account)((HttpServletRequest)req).getSession().getAttribute("account");

        String itemId = (String) ((HttpServletRequest)req).getSession().getAttribute("workingItemId");
        if(itemId == null) itemId = req.getParameter("workingItemId");

        String message =  "";

        if(account!=null)
        {
            message = message + account.getUsername();
        }
        else
        {
            message = message + "A user ";
        }

        if(product != null) {
            WebLog.WriteWebLog(message + " watched " + product.getName());
        }else if (item!=null) {
            WebLog.WriteWebLog(message + " watched " + item.getItemId());
        } else if(category!=null){
            WebLog.WriteWebLog(message + " watched " + category.getCategoryId());
        }else if(cart != null){
            WebLog.WriteWebLog(message + " watched cart" );
        }else if(itemId!=null) {
            WebLog.WriteWebLog(message + " watched " + itemId);
        }

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
